<template>
  <div>
    <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
      <!-- <DeptTree class="w-1/4 xl:w-1/5" @select="handleSelect" /> -->
      <!-- <BasicTable @register="registerTable" class="w-3/4 xl:w-4/5" :searchInfo="searchInfo"> -->
      <div class="acc-list-div">
        <BasicTable @register="registerTable" :searchInfo="searchInfo">
          <template #toolbar v-if="!disableEdit">
            <a-space>
              已排查经营性自建房数量:<Tag color="#55acee">{{ dataTotal }}</Tag> ，抽样数量:<Tag
                color="#55acee"
                >{{ sampleTotal }}</Tag
              >
              ，抽样比例:<Tag color="#55acee">{{
                ((100 * sampleTotal) / dataTotal).toFixed(2)
              }}</Tag
              >%

              <a-button type="primary" @click="handleCreate">新增抽样</a-button>
            </a-space>
          </template>
          <template #districtOne="{ record, column }">
            {{ getDistrictOne(record[column.dataIndex]) }}
          </template>
          <template #districtMany="{ record, column }">
            {{ getDistrictMany(record[column.dataIndex]) }}
          </template>
          <template #action="{ record }">
            <TableAction :actions="GetActions(record)" />
          </template>
        </BasicTable>
      </div>

      <AccountModal
        @register="registerModal"
        @success="handleSuccess"
        width="calc(60vw)"
        :bodyStyle="{ height: 'calc(70vh)' }"
      />

    </PageWrapper>

    <Drawer5 @register="register5">
      <template #drawContent>
        <HouseCheckInfo :samplingId="samplingId" />
      </template>
    </Drawer5>
  </div>
</template>
<script lang="ts">
  import { defineComponent, reactive, ref, toRefs } from 'vue';
  import Drawer5 from '/@/views/detail/Drawer5.vue';
  import { BasicTable, useTable, TableAction, ActionItem } from '/@/components/Table';
  import { getSamplingList, delSampleTasks, getSamplingStat } from '/@/api/demo/system';
  import { PageWrapper } from '/@/components/Page';
  import { useDrawer } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';
  import AccountModal from './AccountModal.vue';
  import HouseCheckInfo from './houseChk/HouseCheckInfo.vue';
  import { Tag, Space, Modal } from 'ant-design-vue';
  import { columns, searchFormSchema } from './account.data';
  import { useGo } from '/@/hooks/web/usePage';
  import {
    downloadByUrl,
    downloadByData,
    downloadByBase64,
    downloadByOnlineUrl,
  } from '/@/utils/file/download';
  import { useGlobSetting } from '/@/hooks/setting';
  const globSetting = useGlobSetting();
  import { useUserStore } from '/@/store/modules/user';
  const userStore = useUserStore();

  export default defineComponent({
    name: 'AccountManagement',
    components: {
      BasicTable,
      PageWrapper,
      HouseCheckInfo,
      Drawer5,
      AccountModal,
      TableAction,
      ASpace: Space,
      Tag,
    },
    props: {
      disableEdit: {
        type: Boolean,
        default: false,
      },
    },
    setup(props) {
      const go = useGo();
      const dataTotal = ref(0);
      const sampleTotal = ref(0);

      getSamplingStat().then((result) => {
        dataTotal.value = result.total;
        sampleTotal.value = result.sampleTotal;
      });

      const { disableEdit } = toRefs(props);
      const [registerModal, { openModal }] = useModal();
      const [registerModal2, { openModal: openModal2 }] = useModal();
      const searchInfo = reactive<Recordable>({});
      const [registerTable, { reload, updateTableDataRecord }] = useTable({
        title: '抽样列表',
        api: getSamplingList,
        rowKey: 'id',
        columns,
        formConfig: {
          schemas: searchFormSchema,
          autoSubmitOnEnter: true,
        },
        useSearchForm: true,
        showTableSetting: true,
        bordered: true,
        handleSearchInfoFn(info) {
          console.log('handleSearchInfoFn', info);
          return info;
        },
        actionColumn: {
          width: 120,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
      });

      function handleCreate() {
        openModal(true, {
          isUpdate: false,
        });
      }

      function getDistrictOne(value) {
        if (value) {
          return value.regionName;
        }
        return value;
      }

      function getDistrictMany(value) {
        if (value) {
          const fds: string[] = [];
          value.forEach((element) => {
            fds.push(element.regionName);
          });

          if (fds.length > 0) {
            return fds.toString();
          }
        }

        return value;
      }

      function handleEdit(record: Recordable) {
        openModal(true, {
          record,
          isUpdate: true,
        });
      }

      const samplingId = ref('');

      const [register5, { openDrawer: openDrawer5, setDrawerProps }] = useDrawer();
      function handlePreview(record: Recordable) {
        samplingId.value = record['id'];
        setDrawerProps({
          destroyOnClose: true,
          showDetailBack: false,
          afterVisibleChange: (visible: boolean) => {
            if (visible) {
            }
          },
        });
        openDrawer5(true);
      }

      function handleDownload(record: Recordable) {
        const samplingIdValue = record['id'];
        const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
        const tk = userStore.getToken;

        downloadByUrl({
          url: `${uriBase}/sample-tasks/${samplingIdValue}/datas/export?access_token=${tk}`,
          target: '_blank',
        });
      }

      function handleEditPwd(record: Recordable) {
        openModal2(true, {
          record,
          isUpdate: true,
        });
      }

      async function handleDelete(record: Recordable) {
        await delSampleTasks(record);
        reload();
      }

      function handleSuccess({ isUpdate, values }) {
        if (isUpdate) {
          // 演示不刷新表格直接更新内部数据。
          // 注意：updateTableDataRecord要求表格的rowKey属性为string并且存在于每一行的record的keys中
          const result = updateTableDataRecord(values.id, values);
          console.log(result);
        } else {
          reload();
        }
      }

      function handleSelect(deptId = '') {
        searchInfo.departmentId = deptId;
        reload();
      }

      function handleView(record: Recordable) {
        go('/system/account_detail/' + record.id);
      }

      function GetActions(record: Recordable): ActionItem[] {
        const edit: ActionItem[] = [
          {
            icon: 'ant-design:delete-outlined',
            color: 'error',
            tooltip: '删除此抽样',
            popConfirm: {
              title: '是否确认删除',
              confirm: handleDelete.bind(null, record),
            },
          },
        ];

        const view: ActionItem[] = [
          {
            icon: 'clarity:tree-view-line',
            tooltip: '核查情况',
            onClick: handlePreview.bind(null, record),
          },
          {
            icon: 'ant-design:export-outlined',
            tooltip: '导出房屋信息',
            onClick: handleDownload.bind(null, record),
          },
        ];

        return disableEdit.value ? view : view.concat(edit);
      }

      return {
        registerTable,
        registerModal,
        registerModal2,
        handleCreate,
        handleEdit,
        handleEditPwd,
        handlePreview,
        handleDownload,
        handleDelete,
        handleSuccess,
        handleSelect,
        handleView,
        searchInfo,
        getDistrictOne,
        getDistrictMany,
        register5,
        samplingId,
        GetActions,
        dataTotal,
        sampleTotal,
      };
    },
  });
</script>
